<template>
  <basic-container>
    <div class="header">
      <TitleComponent mainTitle="代理列表" subTitle="列表" />
      <el-button text type="primary" @click="router.push('/index')">主页</el-button>
    </div>
    <div class="crud_content">
      <avue-crud :option="option" :table-loading="crudData.loading" :data="crudData.data" :page.sync="crudData.page"
        v-model="crudData.form" ref="crud" :before-open="beforeOpen" :before-close="beforeClose" @row-update="rowUpdate"
        @row-save="rowSave" @search-change="searchChange" @refresh-change="refreshChange"
        @selection-change="selectionChange" @search-reset="searchReset" @current-change="currentChange"
        @size-change="sizeChange" @on-load="onLoad">
        <template #code="{ row }">
          <div class="order">
            <el-popover :visible="row.visible" placement="right" :width="200" trigger="click">
              <template #reference>
                <a style="color: #4e9876; border-bottom: dashed 1px #4e9876;" href="javascript:void(0);"
                  @click="row.visible = true">
                  <span v-if="row.code">{{ row.code }}</span>
                  <el-icon v-else>
                    <Edit></Edit>
                  </el-icon>
                </a>
              </template>
              <div class="hover_box">
                <el-input v-model="row.code" placeholder=""></el-input>
                <div style="margin-top: 10px; display: flex;justify-content: flex-end;">
                  <el-button type="" class="btn" @click="row.visible = false">取消</el-button>
                  <el-button color="#4E9876" @click="orderSubmit(row)">提交</el-button>
                </div>
              </div>
            </el-popover>

          </div>
        </template>
        <template #role="{ row }">
          <el-tag color="#4E9876" effect="dark"><span>{{ row.role }}</span></el-tag>
        </template>
        <template #menu="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <el-icon style="rotate: 90deg;cursor: pointer" size="20">
              <More />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">快捷编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item command="fundOperation">代理迁移</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #menu-left="{ row }">
          <el-button class="btn" type="danger" @click="crudData.confirmDeleteVisible = true" v-if="ids.length">
            批量删除
          </el-button>
        </template>
      </avue-crud>
    </div>
    <el-dialog v-model="crudData.confirmDeleteVisible" title="" width="440" destroy-on-close center class="custom-dialog">
      <div class="swal2-header">
        <div class="swal2-icon swal2-question swal2-animate-question-icon"></div>
        <div class="swal2_fs">确认删除？</div>
      </div>
      <div class="swal2_he">ID - {{ crudData.delIds }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#488C6D" class="btn btn-primary" @click="handleDeleteConfirm">
            确认
          </el-button>
          <el-button class="btn" type="" @click="handleDeleteCancel">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="crudData.proxyDialog" title="" width="40%" destroy-on-close center>
      <template #header>
        <div class="header_box">

          被迁移代理:{{ crudData.rowData.ID }}
        </div>
      </template>
      <avue-form v-model="crudData.proxyForm" :option="proxyOption" @submit="submitHandler"></avue-form>
    </el-dialog>
    <el-dialog v-model="crudData.passwordDialog" title="" width="40%" destroy-on-close center>
      <template #header>
        <div class="header_box">

          修改密码
        </div>
      </template>
      <avue-form v-model="crudData.passwordForm" :option="passworOption" @submit="submitPassword"></avue-form>
    </el-dialog>
  </basic-container>
</template>
<script setup lang="ts" name="taskDetail">
import { computed, reactive, ref } from 'vue';
import { getList, remove, update, save, updateAngent, resetPassword } from "@/api/refersh/proxyList.js";

import { ElMessage, ElMessageBox } from "element-plus";
import TitleComponent from '@/components/title/index.vue';
import BasicContainer from "@/components/basic-container/main.vue";
import { useRouter } from "vue-router";
import Cookies from 'js-cookie'
const router = useRouter();
const ids = computed(() => (crudData.selectionList.map(item => item.ID)))
const crud = ref('')
let option: any = reactive({
  align: 'center',
  dialogMenuPosition: 'right',
  saveBtn: true,
  cancelBtn: true,
  emptyBtn: true,
  submitBtn: false,
  height: 'auto',
  calcHeight: '8',
  searchShow: true,
  searchMenuSpan: 6,
  tip: false,
  border: true,
  index: false,
  viewBtn: false,
  editBtn: false,
  delBtn: false,
  addBtn: true,
  dialogWidth: '40%',
  menuFixed: 'right',
  labelWidth: 130,
  menuWidth: 100,
  menu: true,
  selection: true,
  searchLabelWidth: 110,
  indexLabel: '序号',
  saveBtnText: '确定',
  filterBtn: true,
  refreshBtn: true, // 刷新按钮
  columnBtn: false,
  searchShowBtn: false,
  indexWidth: 60,
  dialogDrag: true,
  column: [
    {
      label: "代理编号",
      prop: "userId",
      addDisplay: false,
      sortable: true,
      disabled: true,
      span: 24,
    },
    {
      label: "用户名",
      prop: "userName",
      search: true,
      span: 24,
      prefixIcon: 'el-icon-edit',
      rules: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur',
        },
      ],
    },
    {
      label: "名称",
      prop: "nickName",
      search: false,
      span: 24,
      prefixIcon: 'el-icon-edit',
      rules: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur',
        },
      ],
    },
    {
      label: "头像",
      prop: "avatar",
      type: 'upload',
      hide: true,
      width: 210,
      listType: 'picture-img',
      headers: {
        'Authorization': Cookies.get("Admin-Token")
      },
      dragFile: true,
      limit: 1,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',

      },
      action: '/prod-api/common/upload',
      span: 24,
      rules: [
        {
          required: true,
          message: '请选择图片',
          trigger: 'blur',
        },
      ],
    },
    {
      label: "密码",
      prop: "password",
      hide: true,
      span: 24,
      prefixIcon: 'el-icon-view',
      rules: [
        {
          required: false,
          message: '请输入名称',
          trigger: 'blur',
        },
      ],
    },
    // {
    //   label: "确认密码",
    //   prop: "repassword",
    //   hide: true,
    //   span: 24,
    //   prefixIcon: 'el-icon-view',

    // },
    {
      label: "角色",
      prop: "userType",
      type: 'select',
      dicData: [
        {
          label: '系统用户',
          value: '00'
        },
        {
          label: '代理用户',
          value: '01'
        },
      ],
      span: 24,
      display: false,
    },
    {
      label: "充值",
      prop: "recharge",
      span: 24,
      display: false,

    },
    {
      label: "提现",
      prop: "withdrawal",
      span: 24,
      display: false,

    },
    {
      label: "有效用户",
      prop: "effectiveUser",
      span: 24,
      display: false,

    },
    {
      label: "总用户",
      prop: "userTotal",
      span: 24,
      display: false,

    },
    {
      label: "邀请码",
      prop: "invitationCode",
      placeholder: '邀请码自动生成',
      disabled: true,
      span: 24,
      prefixIcon: 'el-icon-edit',

    },

    {
      label: "创建时间",
      prop: "createTime",
      display: false,
      type: 'datetime',
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      span: 24,
    },
    {
      label: "更新时间",
      prop: "updateTime",
      format: "YYYY-MM-DD HH:mm:ss",
      valueFormat: "YYYY-MM-DD HH:mm:ss",
      display: false,
      hide: true,
      sortable: true,
      type: 'datetime',
      span: 24,
    },
  ]
})
let crudData: any = reactive({
  proxyForm: {},
  passwordDialog: false,
  proxyDialog: false,
  loading: true,
  delIds: '',
  selectionList: [],
  confirmDeleteVisible: false,
  form: {
    edit: true,
    creat: "",
    view: "",
  },
  page: {
    pageSize: 10,
    currentPage: 1,
    total: 1,

  },
  openTyep: '',
  query: {},
  data: []
})
let passworOption: any = reactive({
  // labelWidth: 150,
  column: [
    {
      label: '新密码',
      prop: 'password',
      type: 'password',
      showPassword: true,
      span: 24,
      rules: [
        {
          required: true,
          message: '请输入新密码',
          trigger: 'blur',
        },
      ],
    }
  ]
})
let proxyOption: any = reactive({
  labelWidth: 150,
  column: [
    {
      label: '选择迁移目标代理',
      prop: 'newAgentId',
      span: 24,
      type: 'select',
      props: {
        label: 'userName',
        value: 'userId'
      },
      dicData: [],
      rules: [
        {
          required: true,
          message: '请选择迁移目标代理',
          trigger: 'blur',
        },
      ],
    }
  ]
})
const refreshChange = () => {
  onLoad(crudData.page);
}
const delsHandler = () => {
  if (crudData.selectionList.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // return remove(this.ids);
    })
    .then(() => {
      // onLoad(crudData.page);
      ElMessage.success('操作成功');
    });
}

const handleDeleteCancel = () => {
  crudData.confirmDeleteVisible = false;
}
const handleDeleteConfirm = async () => {
  await remove(crudData.delIds)
  crudData.confirmDeleteVisible = false;
  onLoad(crudData.page)
}
const submitPassword = async (row) => {
  let params = {
    "userId": crudData.rowData.userId,
    "password": row.password
  }
  await resetPassword(params)
  console.log('row====', row);
  crudData.passwordDialog = false
  ElMessage.success('操作成功');
}
const submitHandler = async (row) => {
  let params = {
    sourceAgentId: crudData.rowData.userId,
    newAgentId: row.newAgentId
  }
  await updateAngent(params)
  console.log('row====', row);
  crudData.proxyDialog = false
  ElMessage.success('操作成功');
}
const handleCommand = (command, row) => {
  crudData.rowData = row
  if (command === 'edit') {
    crud.value.rowEdit(row)
  } else if (command === 'delete') {
    crudData.delIds = row.userId
    crudData.confirmDeleteVisible = true;
  } else if (command === 'fundOperation') {
    crudData.proxyDialog = true;
    crudData.delIds = row.userId
    let arr = crudData.data.filter(item => item.userName != row.userName)
    proxyOption.column[0].dicData = arr
  } else if (command === 'password') {
    crudData.passwordDialog = true
  }
};

const handleSubmit = () => {
  crud.value.validate((valid: any, done: () => void, msg: any) => {
    if (valid) {
      ElMessage.success('操作成功');
      setTimeout(() => {
        done()
      }, 2000)
    }
  })
}
const selectionChange = (list) => {
  crudData.selectionList = list
}
const handleEmpty = () => {
  crud.value.resetForm();
}
// 序号按钮提交
const orderSubmit = (row: { visible: boolean; }) => {
  row.visible = false
  console.log('row====', row);
}

// 翻页
function currentChange(currentPage: any) {
  crudData.page.currentPage = currentPage;
}

// 每页条数
function sizeChange(pageSize: any) {
  crudData.page.pageSize = pageSize;
}

// 重置
function searchReset() {
  crudData.query = {};
  onLoad(crudData.page);
}

// 列表模糊搜索
function searchChange(params: {} | undefined, done: () => void) {
  crudData.query = params;
  crudData.page.currentPage = 1;
  onLoad(crudData.page, params);
  done();
}

// 删除
const rowSave = async (row: any, done: any, loading: any) => {
  await save(row)
  ElMessage.success('操作成功');
  onLoad(crudData.page);
  done()
}
const rowUpdate = async (row: any, index: Number, done: any, loading: any) => {
  await update(row)
  ElMessage.success('操作成功');
  onLoad(crudData.page);
  done()

}

// 弹窗打开前
function beforeOpen(done: any, type: any) {
  // type :类型 add -添加 edit -编辑 view -查看
  if (["add"].includes(type)) {
    option.column.find(item => item.prop === 'password').rules[0].required = true
  }
  if (type === 'edit') {
    option.column.find(item => item.prop === 'password').rules[0].required = false
  } else {
  }
  done() //  关闭弹窗
}

// 弹窗关闭前
const beforeClose = (done: () => void, type: any) => {

  done() //  关闭弹窗
}
const changeName9 = (res: any, row: any) => {
  console.log('row', row);
  console.log('res', res);
}
const onLoad = (page, params = {}) => {
  crudData.loading = true;
  getList(page.currentPage, page.pageSize, Object.assign(params, crudData.query)).then(res => {
    console.log('getReviewLog--', res);
    const Data = res.rows;
    crudData.page.total = res.total;
    crudData.data = Data
    // .map(item=>({...item,rent: '12-24'}));
    crudData.loading = false;
  });
}
</script>
<style scoped lang="scss">
.header_box {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 18px;
  margin-bottom: 20px;

}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 2%;
}

.crud_content {
  width: 100%;
}

::v-deep span.avue-crud__img {
  width: 50px;
  height: 30px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

::v-deep .el-popper {

  .hover_box {

    .btn_box {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;

      .btn {
        margin-right: 10px;
      }
    }
  }
}

.custom-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.swal2-header {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.swal2-icon {
  position: relative;
  box-sizing: content-box;
  justify-content: center;
  width: 5em;
  height: 5em;
  margin: 1.25em auto 1.875em;
  zoom: normal;
  border: 0.25em solid transparent;
  border-radius: 50%;
  line-height: 5em;
  cursor: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.swal2-icon.swal2-question::before {
  content: "?";
}

.swal2-icon::before {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 92%;
  font-size: 3.75em;
}

.swal2-icon.swal2-question {
  border-color: #c9dae1;
  color: #87adbd;
}

.swal2_fs {
  margin: 0 0 0.4em;
  padding: 0;
  font-size: 25px;
  color: #595959;
  text-align: center;
  font-weight: 400 !important;
}

.swal2_he {
  text-align: center;
  color: #545454;
  font-size: 1.125em;
  font-weight: 300;
  line-height: normal;
  word-wrap: break-word;
}
</style>
